<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of rpp
 *
 * @author Edgar Drake
 */
class RPP extends CI_Controller {

    public function __construct() {
        global $userdb, $itemdb, $competencedb;
        parent::__construct();
        
        // Database Connection
        $connection = new Mongo('localhost:27017'); // Connect to Mongo
        $db = $connection->rpp; // Select a database
        $itemdb = $db->item; // Select a collection
        $userdb = $db->user;
        $competencedb = $db->competence;
    }

// <editor-fold defaultstate="collapsed" desc="Region: RPP Item creator">
    
    /**
     * Create a new RPP item and store to DB.
     */
    public function create() {
        global $itemdb;

        $title = $_POST['title'];
        $status = 'draft';
        $author = $_POST['author'];
        $desc = $_POST['description'];
                
//        // Activities
//        $activities = array(
//            "learn-approach"    => $_POST['learn-approach'],
//            "learn-methods"     => explode("\r\n", $_POST['learn-methods']),
//            "start-act"         => $this->_readActivity("start-act"),
//            "exploration"       => $this->_readActivity("exploration"),
//            "elaboration"       => $this->_readActivity("elaboration"),
//            "conformation"      => $this->_readActivity("conformation"),
//            "closing-act"       => $this->_readActivity("closing-act")
//        );
        
        $data = array(
            "school"            => $_POST['school'],
            "class"             => $_POST['class'],
            "term"              => $_POST['term'],
            "topic"             => $_POST['topic'],
            "theme"             => $_POST['theme'],
            "related-subjects"  => $_POST['related-subjects'],
            "subjects"          => $this->_subjects(),
            "goals"             => explode("\r\n", $_POST['goals']),
            "materials"         => $_POST['materials'],
//            "activities"        => $this->_activities(), // untested
            "resource"          => explode("\r\n", $_POST['resource']),
            "assessment"        => $this->_assessment()
        );

        $itemdata = array(
            "title"         => $title,
            "author"        => array($author),            
            "description"   => $desc,
            "lookup"        => strtolower($desc),
            "tags"          => explode(',', $_POST['tags']),
            "status"        => $status,
            "data"          => $data
        );
        $itemdb->insert($itemdata);
        echo "add-item-success";
    }
    
    /**
     * Create action appropriate to it's parameter.
     * Parameter $phase may only use this kind of string:
     * 1: "start-act"
     * 2: "exploration"
     * 3: "elaboration"
     * 4: "conformation"
     * 5: "closing-act"
     * @param string $phase Teaching phase in class.
     */
    private function _readActivity($phase) {
        $output = array();
        $count = $_POST[$phase . '-count'];
        for ($i = 0; $i < $count; $i++) {
            $output["activity"][$i] = $_POST[$phase . '-activity-' . $i];
            $output["duration"]     = $_POST[$phase . '-duration']; 
        }
        return $output;
    }
    
    /**
     * Compose multiple activities into a composite object
     * @return composite RPP activities
     */
    private function _activities() {
        $activities = array(
            "learn-approach" => $_POST['learn-approach'],
            "learn-methods"  => explode("\r\n", $_POST['learn-methods']),
            "start-act"      => $this->_readActivity("start-act"),
            "core-act"       => $this->_readActivity("core-act"),
            "closing-act"    => $this->_readActivity("closing-act")
        );
        return $activities;
    }
    
    /**
     * Read assessment data. Assessment is divided into 3 types:
     * Multiple choice: A-D options, only one correct.
     * Essay: scoring is based on students matching/related keywords
     * Quiz: fill the blank, literally.
     * @return type Assessment composition item.
     */
    private function _assessment() {
        $output = array();
        // Multiple Choices
        $countMP = intval($_POST['mc-count']);
        if ($countMP > 0) {
            for ($i = 0; $i < $countMP; $i++) {
                $output["multiple-choice"][$i]["indicator"] = $_POST['mc-indicator-' . $i];
                $output["multiple-choice"][$i]["question"]  = $_POST['mc-question-' . $i];
                $output["multiple-choice"][$i]["options"]   = explode("\r\n", $_POST['mc-options-' . $i]);
                $output["multiple-choice"][$i]["solution"]  = $_POST['mc-solution-' . $i];
                $output["multiple-choice"][$i]["score"]     = $_POST['mc-score-' . $i];
            }
        }
        // Essays
        $countES = intval($_POST['es-count']);
        if ($countES > 0) {
            for ($i = 0; $i < $countES; $i++) {
                $output["essay"][$i]["indicator"]   = $_POST['es-indicator-'. $i];
                $output["essay"][$i]["question"]    = $_POST['es-question-'. $i];
                for ($j = 0; $j < $_POST['es-solution-count']; $i++) {
                    $output["essay"][$i]["solutions"][$j]["key-point"]  = $_POST['es-solution-answer-'. $j];
                    $output["essay"][$i]["solutions"][$j]["score"]      = $_POST['es-solution-score-'. $j];
                }
            }
        }
        // Simple Quizes
        $countSQ = intval($_POST['sq-count']);
        if ($countSQ > 0) {
            for ($i = 0; $i < $countSQ; $i++) {
                $output["simple-quiz"][$i]["indicator"] = $_POST['sq-indicator-' . $i];
                $output["simple-quiz"][$i]["question"]  = $_POST['sq-question-' . $i];
                $output["simple-quiz"][$i]["solution"]  = $_POST['sq-solution-' . $i];
                $output["simple-quiz"][$i]["score"]     = $_POST['sq-score-' . $i];
            }
        }
        return $output;
    }
    
    /**
     * Compose subjects which should be covered by teaching material.
     * @return Composition Composition of related subjects
     */
    private function _subjects() {
        // Subjects
        $countSubjects = $_POST['subject-count'];
        $subjects = array();
        for ($i = 0; $i < $countSubjects; $i++) {
            $subjects[$i]["subject-name"]       = $_POST['related-subjects'][$i];
            $subjects[$i]["core-competence"]    = $_POST['core-competence-' . $i];
            $subjects[$i]["basic-competence"]   = explode("\r\n", $_POST['basic-competence-' . $i]);
            $subjects[$i]["indicator"]          = explode("\r\n", $_POST['indicator-' . $i]);
        }
        return $subjects;
    }


    /*
     * Get list of RPP items in appropriate query
     * @param string $query Query needs to be executed. Leave it empty to get all.
     */
    public function lists($query = NULL) {
        global $itemdb;
        $format = array("title" => true, "author" => true);
        if ($query == NULL) {
            $item_cursor = $itemdb->find(array(), $format);
        }
        foreach ($item_cursor as $cursor) {
            $items[] = $cursor;
        }
        echo json_encode($items);
    }
    
    /* Get a detailed view of item
     * @param string $id MongoID of RPP item. Automatically unique.
     */
    public function get($id) {
        global $itemdb;
        $item = $itemdb->findOne(array('_id' => new MongoId($id)));
        echo json_encode($item);
    }
    
    /* Look for RPP item which match the criteria
     * @param type $param
     */
    public function search($param) {
        global $itemdb;
        
        $params = explode(" ", $param);
        $format = array("_id" => true, "title" => true, "description" => true, "author" => true);
        
        for ($i = 0; $i < count($params); $i++) {
            $paramOR[$i] = array(
                '$or' => array(
                    array('author'      => new MongoRegex("/".$params[$i]."/")),
                    array('title'       => new MongoRegex("/".$params[$i]."/")),
                    array('description' => new MongoRegex("/".$params[$i]."/")),
                    array('status'      => new MongoRegex("/".$params[$i]."/")),
                    array('data.school' => new MongoRegex("/".$params[$i]."/")),
                    array('data.topic'  => new MongoRegex("/".$params[$i]."/")),
                    array('data.core-competence'  => new MongoRegex("/".$params[$i]."/")),
                    array('data.basic-competence' => new MongoRegex("/".$params[$i]."/")),
                    array('data.learn-indicator'  => new MongoRegex("/".$params[$i]."/")),
                    array('data.goals'            => new MongoRegex("/".$params[$i]."/")),
                    array('data.materials'        => new MongoRegex("/".$params[$i]."/")),
                    array('data.learn-method.method'        => new MongoRegex("/".$params[$i]."/")),
                    array('data.learn-method.start-act'     => new MongoRegex("/".$params[$i]."/")),
                    array('data.learn-method.exploration'   => new MongoRegex("/".$params[$i]."/")),
                    array('data.learn-method.elaboration'   => new MongoRegex("/".$params[$i]."/")),
                    array('data.learn-method.conformation'  => new MongoRegex("/".$params[$i]."/")),
                    array('data.learn-method.closing-act'   => new MongoRegex("/".$params[$i]."/")),
                    array('data.assessment.method'          => new MongoRegex("/".$params[$i]."/")),
                    array('data.assessment.form'            => new MongoRegex("/".$params[$i]."/")),
                    array('data.assessment.instrument'      => new MongoRegex("/".$params[$i]."/"))
                )
            );
        }
        $paramAND = array('$and' => $paramOR);
        
        $items = NULL;                
        $item_cursor = $itemdb->find(
            //$paramOR[0], $format // format message output OK, tested 1 param
            $paramAND, $format
        );
        foreach ($item_cursor as $cursor) {
            $items[] = $cursor;
        }
        echo json_encode($items);
    }

    public function index() {
        $filename = 'd-create';
//        $filename = 'editor';
        if (!file_exists('application/views/'.$filename.'.php')) {
            // Whoops, we don't have a page for that!
            show_404();
        }
        //$this->load->view('create');
        $this->load->view($filename);
    }
    
    public function viewSearch() {
        $query = $this->input->get('query');
        if ($query != NULL) {
            $this->search($query);
        } else {
            $this->load->view('d-search');
        }
    }
// </editor-fold>
    
// <editor-fold defaultstate="collapsed" desc="Region: Competence">
    public function addCompetence() {
        global $competencedb;
        $competence = array(
            "class"  => $_POST['class'],
            "term"   => $_POST['term'],
            "core"   => $_POST['core'],
            "basics" => explode("\r\n", $_POST['basics'])
        );        
        $competencedb->insert($competence);
        echo 'add-competence success';
    }
    
    public function competence() {
        $this->load->view('competence');
    }
// </editor-fold>

}

?>
